package com.hb.common.util;

import com.hb.common.dto.Database;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class PathPermissions {

    private static final Logger log = LoggerFactory.getLogger(PathPermissions.class);

    /**
     * 获取配置路径
     */
    public String getConfigPath() {
        return this.getBasePath() + "/config/";
    }

    /**
     * 获取数据库程序路径
     */
    public String getDbProgramPath() {
        return this.getBasePath() + "/config/dbProgram/";
    }

    /**
     * 获取数据库备份文件路径
     */
    public String getDbBackupPath(Database database) {
        return this.getBasePath()
                + "/dbBackupFile/"
                + database.getHost() + "/"
                + database.getDbType() + "/"
                + database.getDbName() + "/";
    }

    /**
     * 获取路径
     */
    public String getBasePath() {
        return getWritablePath() + "/db-backup";
    }

    /**
     * 获取有读写权限的路径
     * 默认取 [当前用户的目录] 和 [当前程序运行的路径]
     */
    public String getWritablePath() {
        // 获取系统当前用户的目录
        String userHome = System.getProperty("user.home").replace("\\", "/");
        if (hasReadWritePermissions(userHome)) {
            return userHome;
        }

        // 获取当前程序运行的路径
        String currentPath = System.getProperty("user.dir").replace("\\", "/");
        if (hasReadWritePermissions(currentPath)) {
            return currentPath;
        }

        log.error("未找到可用目录");
        return null;
    }

    /**
     * 判断目录是否有读写权限
     *
     * @param path 目录
     */
    private boolean hasReadWritePermissions(String path) {
        CommonUtil.validateOrCreateDirectory(path);
        File file = new File(path);
        return file.exists() && file.canRead() && file.canWrite();
    }

}
